package com.code2roc.fastboot.framework.security;

import com.alibaba.fastjson.JSONObject;
import com.code2roc.fastboot.framework.util.CommonUtil;
import com.code2roc.fastboot.framework.util.DESEncryptUtil;
import com.code2roc.fastboot.framework.util.RSAEncryptUtil;
import com.code2roc.fastboot.framework.util.StringUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class XSSBodyRequestWrapper extends HttpServletRequestWrapper {

    private String body;

    public XSSBodyRequestWrapper(HttpServletRequest request) {
        super(request);
        try{
            body = XSSScriptUtil.handleString(CommonUtil.getBodyString(request));
            String encrypt = request.getHeader("encrypt");
            if (!StringUtil.isEmpty(encrypt)) {
                String privateKey = RSAEncryptUtil.getSystemDefaultRSAPrivateKey();
                String desEncryptStr = RSAEncryptUtil.decryptPKSC1(encrypt, privateKey);
                JSONObject obj = JSONObject.parseObject(body);
                String encryptParam = obj.getString("encryptParam");
                body = DESEncryptUtil.decrypt(encryptParam, desEncryptStr);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8")));

        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

}
